package com.djt.book_system.controller;

import com.djt.book_system.entity.Books;
import com.djt.book_system.service.BooksService;
import com.djt.book_system.service.BorrowsService;
import com.djt.book_system.util.Result;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * (Books)表控制层
 *
 * @author makejava
 * @since 2021-05-19 10:48:09
 */
@RestController
@RequestMapping("books")
public class BooksController {
    /**
     * 服务对象
     */
    @Resource
    private BooksService booksService;
    @Resource
    private BorrowsService borrowsService;

    /**
     * 通过主键查询单条数据
     *
     * @param bid 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public Books selectOne(Integer bid) {
        return this.booksService.queryById(bid);
    }

    /**
     * 分页查询所有数据
     *
     * @param page 页码
     * @param limit 每页数据条数
     * @return book对象集合
     */
    @GetMapping("select")
    public Result select(int page, int limit , Books conditional){//页码，每页数据条数，条件
        //每页起始位置
        int offset = (page-1)*limit;
        //查询满足条件的数据
        List<Books> books = booksService.queryAllByLimit(offset,limit,conditional);
        //查询满足条件的数据条数
        int count = booksService.booksCount(conditional);
        if (books.size()==0){//如果查询结果为空
            try {
                //查询上一页数据
                offset = (page-1-1)*limit;
                books = booksService.queryAllByLimit(offset,limit,conditional);
                //封装
                return Result.success(count,books);
            }catch (Exception e){
                return Result.success(0,null);
            }
        }
        //封装
        return Result.success(count,books);
    }

    /**
     * 添加book数据
     *
     * @param books book对象
     */
    @PostMapping("addOne")
    public void addOne(Books books){
        //添加一条书籍记录并返回主键
        booksService.insert(books);
        //设置书籍剩余数量
        books.setSurplusnum(books.getTotalnum()-borrowsService.borrowCountById(books.getBid()));
        //将剩余数量set进books对象并更新数据
        booksService.update(books);
    }

    /**
     * 更新一条数据
     *
     * @param books book对象
     */
    @PostMapping("updateOne")
    public void updateOne(Books books){
        booksService.update(books);
    }

    /**
     * 根据主键删除数据
     *
     * @param bid 主键
     */
    @GetMapping("deleteOne")
    public void deleteOne(int bid){
        booksService.deleteById(bid);
    }
    @GetMapping("batchRemove")
    public void batchRemove(int[] bids){
        booksService.batchRemove(bids);
    }

}
